import 'dart:io';

import 'package:camera/camera.dart';
import 'package:dio/dio.dart' as dio;
import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_bool_entity.dart';
import 'package:largefriends/entity/entities/lf_gesture_entity.dart';
import 'package:video_player/video_player.dart';
import 'package:video_thumbnail/video_thumbnail.dart' as thumb;

import '../../../entity/entities/lf_photo_entity.dart';
import '../../../events/user_change_event.dart';
import '../../../service/manager/lf_event_helper.dart';
import '../../../net/error_handle.dart';
import '../../../net/lf_api_url.dart';
import '../../../net/lf_dio_util.dart';
import '../../../res/strings/lf_strings.dart';
import '../../../service/lf_auth_service.dart';
import '../../../utils/lf_dialog_utils.dart';
import '../../../widgets/dialog_action_tip.dart';

toVerifyCameraConfirm({required LfGestureEntity entity, required XFile video}) {
  Get.offAndToNamed(LFRoute.pathVerifyCameraConfirm,
      arguments: {'gestureEntity': entity, 'video': video});
}

class LfVerifyCameraConfirmLogic extends GetxController {
  late LfGestureEntity gesture;
  late XFile video;
  late VideoPlayerController controller;

  @override
  void onInit() {
    gesture = Get.arguments['gestureEntity'];
    video = Get.arguments['video'];
    controller = VideoPlayerController.file(File(video.path))
      ..setLooping(true)
      ..initialize().then((_) {
        update();
        controller.play();
      }, onError: (error) {});
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  verifyVideo() async {
    showLoading();
    final uint8list = await thumb.VideoThumbnail.thumbnailData(
      video: video.path,
      imageFormat: thumb.ImageFormat.JPEG,
      maxWidth: 128,
      // specify the width of the thumbnail, let the height auto-scaled to keep the source aspect ratio
      quality: 25,
    );

    var thumbId = "";
    if (uint8list != null) {
      var formData = dio.FormData();
      formData.files.add(MapEntry(
          'file',
          dio.MultipartFile.fromBytes(uint8list,
              filename: DateTime.now().microsecondsSinceEpoch.toString())));
      formData.fields.add(const MapEntry('photoType', "10"));
      formData.fields.add(const MapEntry('protect', "1"));
      await LfDio()
          .post<List<LfPhotoEntity>>(
        url: apiUploadFile,
        params: formData,
        // onSendProgress: onSendProgress,
      )
          .then((value) {
        if (value.isNotEmpty) {
          thumbId = value.first.attachId ?? "";
        }
      });
    }
    var videoFormData = dio.FormData();
    var videoBytes = await video.readAsBytes();
    videoFormData.files.add(MapEntry(
        'file', dio.MultipartFile.fromBytes(videoBytes, filename: video.name)));
    videoFormData.fields.add(const MapEntry('photoType', "10"));
    videoFormData.fields.add(const MapEntry('protect', "1"));
    var videoId = "";
    await LfDio()
        .post<List<LfPhotoEntity>>(
      url: apiUploadFile,
      params: videoFormData,
      // onSendProgress: onSendProgress,
    )
        .then((value) {
      if (value.isNotEmpty) {
        videoId = value.first.attachId ?? "";
      }
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });

    if (videoId.isEmpty) {
      return;
    }
    await LfDio().post<LfBoolEntity>(
      url: apiVerifyByVideo,
      params: {'videoId': videoId, 'videoCoverId': thumbId},
      // onSendProgress: onSendProgress,
    ).then((value) {
      hideLoading();
      showActionTips(
          tips: strVerifyDone.tr,
          actionButtonTip: strOK.tr,
          action: () {
            Get.back();
            LfAuthService service = Get.find();
            service.currentAccount!.verified = 2;
            service.currentAccount!.mandatoryVerificationFlag = 0;
            service.setUserEntity(service.currentAccount);
            LfEventHelper().getEvent().fire(
                UserChangeEvent(userChangeAction: UserChangeAction.verify));
          },
          showCancel: false,
          dismissible: false);
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }

  @override
  void onClose() {
    controller.pause();
    controller.dispose();
    super.onClose();
  }
}
